package com.miplus.ccrm.core.service;

import com.miplus.ccrm.common.EnumRCode;
import com.miplus.ccrm.common.JPubUtils;
import com.miplus.ccrm.common.ServiceException;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.UUID;

@Slf4j
@Service
public class JRbtLinker {
    @Value("${ccrm.dialer.rbturi:}")
    public String dialer_rbturi;
    @Value("${ccrm.dialer.rbtqueue:}")
    public String dialer_rbtqueue;

    public int SendDialerCmd(String msg)
    {
        int ret=-1;
        log.info("Rbt.SendCmd({}):uri={}",dialer_rbtqueue,dialer_rbturi);
        if(JPubUtils.IsEmpty(dialer_rbturi)){
            throw new ServiceException(EnumRCode.NoFindConfig.value, EnumRCode.NoFindConfig.name);
        }
        try {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setUri(dialer_rbturi);
            Connection conn = factory.newConnection("dialrbtconn");
            Channel channel = conn.createChannel();

            String uid= UUID.randomUUID().toString();
            log.info("Rbt.SendCmd({}):replyTo={},msg={}",dialer_rbtqueue,uid,msg);

            channel.basicPublish("", dialer_rbtqueue, new AMQP.BasicProperties.Builder()
                            .replyTo(UUID.randomUUID().toString())
                            .build(),
                    msg.getBytes("utf-8"));
            log.info("Rbt.SendCmd({}):done",dialer_rbtqueue);
            channel.close();
            conn.close();
            ret=0;
            log.info("Rbt.SendCmd({}):Ok",dialer_rbtqueue);
        }
        catch (Exception e){
            log.warn("Rbt.Exception:{}",e.getMessage());
            throw new ServiceException(EnumRCode.CmdFail.value, e.getMessage());
        }

        return ret;
    }
}
